<?php
namespace app\store\controller\shop;

use app\store\controller\Controller;
/**
 * 机油库存管理
 * Class Index
 * @package app\store\controller
 */
class Stock extends Controller
{
    public function index()
    {
        $id = $this->request->param("id/d" , 0);
        if( $id <= 0 ) $this->error('信息传递错误');
        $info = db("engineoil")->where(['id' => $id])->find();
        if( !$info ) $this->error("机油数据不存在");
        $list = db("engineoil_stock_log")->where(['eid' => $id , 'is_delete' => 1])->order(['id' => 'DESC'])->paginate(15, false, ['query' => $this->request->request()])->each(function($item , $key){
            $item['shop_name'] = '';
            if( $item['shop_id'] > 0 ) {
                $item['shop_name'] = db("shop")->where(['shop_id' => $item['shop_id']])->value("shop_name");
            }
            return $item;
        });
        $count_data = [
            'go' => db("engineoil_stock_log")->where(['type' => ['in','1,4'] , 'eid' => $id])->sum("stock"),
            'out' => db("engineoil_stock_log")->where(['type' => ['in','2,3'] , 'eid' => $id])->sum("stock"),
        ];
        return $this->fetch('index', compact('list' , 'info' , 'count_data'));
    }
    
    public function add() {
        $id = $this->request->param("id/d" , 0);
        if( $id <= 0 ) $this->error('信息传递错误');
        $info = db("engineoil")->where(['id' => $id])->find();
        if( !$info ) $this->error("机油数据不存在");
        if( $this->request->isAjax()) {
            $params = $this->postData('poster');
            $params['eid'] = $info['id'];
            $params['create_time'] = time();
            $res = db('engineoil_stock_log')->insert($params);
            if( $res ) {
                $stocks = $params['type'] == 1 ? $info['stock'] + $params['stock'] : $info['stock'] - $params['stock'];
                db("engineoil")->where(['id' => $info['id']])->update(['stock' => $stocks]);
                $this->success('库存调整成功' , url("shop.stock/index" , array("id" => $id)));
            } else {
                $this->error("库存调整失败，请重试");
            }
        }
        $template_type = 'tips';
        return $this->fetch('' , compact('info' , 'template_type'));
    }
    
    public function delete() {
        $id = $this->request->post('id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('engineoil_stock_log')->where(['id' => $id])->update(['is_delete' => 0]);
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
}
